import service from "./request"
const baseUrl = 'http://uploader.weather.hywea.cn:30080'


// 处理分片
const multipartUpload = async (file, size) => {
    console.log(file,size);
    // file:文件
    // szie:分片每块的大小 MB
    let fileType = file.type // 文件的类型
    let chunkSize = size * 1024 *1024 //块大小
    let start = 0
    let end = chunkSize
    let totalChunks = Math.ceil(file.size / chunkSize)
    let chunkIndex = 1
    const startUpload = await startUploadFile(fileType)
    const completedParts = []    
    while (start < file.size) {
        const chunk = file.slice(start,end)
        console.log(`分片${chunkIndex}/${totalChunks}`);
        console.log(`当前分片大小: ${chunk.size}`);
        const fs = new FormData()
        fs.append('file', chunk)
        fs.append('upload_id', startUpload.upload_id)
        fs.append('s3_path', startUpload.s3_path)
        fs.append('part_number', chunkIndex.toString())
        const uploading = await uploadingFile(fs)
        completedParts.push(uploading)
        start = end;
        end = start + chunkSize;
        chunkIndex++;
    }
    const finishUpload = await finishUploadFile(startUpload.upload_id, startUpload.s3_path,completedParts)
    console.log(finishUpload);
    return finishUpload.location
}

// 开始上传
const startUploadFile = async (fileType) => {
    console.log(fileType);
    const res = await service({
        method: 'post',
        url: `${baseUrl}/s3-uploader/api/v1/multipart/create`,
        data:{
            mime_type: fileType,
        }
    })
    return res.data
}
// 分片上传中
const uploadingFile = async (fs) => {
    const res = await service.post(`${baseUrl}/s3-uploader/api/v1/multipart/upload`,fs)
    return res.data
}
// 完成分块上传
const finishUploadFile = async (id,path,completedParts) => {
    const res = await service({
        method:'post',
        url:`${baseUrl}/s3-uploader/api/v1/multipart/complete`,
        data:{
            upload_id: id,
            s3_path: path,
            parts: completedParts
        }
    })
    return res.data
}
// 取消上传
const source = axios.CancelToken.source()
source.cancel('用户已取消上传');

export default multipartUpload;